package com.jsmile.cloud.authc.sys.repo;

import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jsmile.cloud.authc.api.enums.AuthcCodeEnum;
import com.jsmile.cloud.authc.api.exception.AuthcException;
import com.jsmile.cloud.authc.api.req.sys.ReqSysDictQuery;
import com.jsmile.cloud.authc.api.req.sys.ReqSysDictUpdate;
import com.jsmile.cloud.authc.sys.dao.SysDictionaryDao;
import com.jsmile.cloud.authc.sys.model.SysDictionary;
import com.jsmile.mall.api.kit.StrKit;

import lombok.extern.slf4j.Slf4j;

/**
 * @author 龚亮
 * @version 1.0
 * @desc 为了薪资破万，还是睡一会儿吧...!
 * @date 2020年10月16日 02:46:20
 */
@Service
@Slf4j
@Transactional(readOnly = false, rollbackFor = Exception.class)
public class SysDictionaryRepository extends ServiceImpl<SysDictionaryDao, SysDictionary> {

    public boolean deleteDict(ReqSysDictUpdate reqSysDictUpdate) {
        int i = this.baseMapper.delete(new UpdateWrapper<SysDictionary>().lambda().eq(SysDictionary::getParentId, reqSysDictUpdate.getParentId()));
        i += this.baseMapper.deleteById(reqSysDictUpdate.getId());
        return retBool(i);
    }

    public boolean saveDict(ReqSysDictUpdate reqSysDictUpdate) {
        if (StrKit.notBlank(reqSysDictUpdate.getDictCode())) {
            ReqSysDictQuery query = new ReqSysDictQuery();
            query.setDictCode(reqSysDictUpdate.getDictCode());
            List<SysDictionary> lists = baseMapper.findDictByCode(query);
            if (!CollectionUtils.isEmpty(lists)) {
                throw new AuthcException(AuthcCodeEnum.DICT_COTE_EXISTS);
            }
        }
        return retBool(baseMapper.insert(SysDictionary.create(reqSysDictUpdate)));
    }
}
